package io.renren.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import io.renren.modules.zjwl.entity.SimCardEntity;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ExcelReadUtils {

    public static List<SimCardEntity> analysisSimCard(MultipartFile file) {
        List<SimCardEntity> simCardEntityList = new ArrayList<>();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (suffix.equalsIgnoreCase(".xlsx")) {
            return readXlsx(file);
        } else if (suffix.equalsIgnoreCase(".xls")) {
            return readXls(file);
        }

        return simCardEntityList;
    }

    public static List<SimCardEntity> readXls(MultipartFile file) {
        List<SimCardEntity> simCardEntityList = new ArrayList<>();

        return simCardEntityList;
    }

    public static List<SimCardEntity> readXlsx(MultipartFile file) {
        List<SimCardEntity> simCardEntityList = new ArrayList<>();
        InputStream inputStream = null;
        XSSFWorkbook wb = null;
        try {
            inputStream = file.getInputStream();
            wb = new XSSFWorkbook(inputStream);
            if (wb.getNumberOfSheets() > 0) {
                XSSFSheet xssfSheet = wb.getSheetAt(0);
                int totalRows = xssfSheet.getLastRowNum();
                for (int rowNum = 1; rowNum <= totalRows; rowNum++) {
                    XSSFRow row = xssfSheet.getRow(rowNum);
                    if (row != null) {
                        SimCardEntity simCardEntity = new SimCardEntity();
                        simCardEntity.setSimCode(row.getCell(1).getStringCellValue());
                        simCardEntity.setMobile(row.getCell(0).getStringCellValue());
                        Date activeDate = DateUtil.parse(row.getCell(2).getStringCellValue(), "yyyy/MM/dd");
                        simCardEntity.setActivedate(activeDate);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(activeDate);
                        int leftMonth = Integer.parseInt(row.getCell(3).getStringCellValue());
                        calendar.add(Calendar.MONTH, leftMonth);
                        simCardEntity.setExpireDate(calendar.getTime());
                        simCardEntityList.add(simCardEntity);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return simCardEntityList;
    }
}
